package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eOrderStatus;
import com.yanqu.road.entity.enums.ePreChargeType;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.logic.bussiness.recharge.RechargeBussiness;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.order.OrderHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseGameHttpServlet;
import com.yanqu.road.web.mgr.InnerUserMgr;
import com.yanqu.road.web.mgr.MallMgr;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/precharge")
public class PreCharge extends BaseGameHttpServlet {

    private static Logger logger = LogManager.getLogger(PreCharge.class.getName());

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpGameWebParam httpGameWebParam = super.parseRequest(request);
        JSONObject paramObj = httpGameWebParam.getParamObj();
        String param = httpGameWebParam.getParam();
        String language = httpGameWebParam.getLanguage();
        JSONObject resultObj;
        int ret = 0;
        int type;
        long userId;
        int mallId;
        int activityId = 0;
        int conditionId = 0;
        long couponItemId = 0;
        //铁人三项活动服直接不能充值
        ServerInfo serverInfo = ServerListMgr.getServerInfo(WebServer.getInstance().getServerId());
        if(null != serverInfo && serverInfo.getServerType() == ServerListMgr.SERVER_TYPE_ACTIVITY) {//三方活动服不能充值
            resultObj = getResultObj(GameErrorCode.E_RECHARGE_FAIL, language);
            sendMessage(response, resultObj.toJSONString());
            return;
        }
        try {
            type = paramObj.getIntValue("type");
            userId = paramObj.getLong("playerId");
            mallId = paramObj.getIntValue("goodId");
            couponItemId = paramObj.getLongValue("couponItemId");
        } catch (Exception e) {
            resultObj = getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge json格式出错！ json 字符串param为{}", param, e);
            return;
        }
        if(userId <= 0){
            resultObj = getResultObj(GameErrorCode.E_PRE_CHARGE_USER_ID_ERROR, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge fail, userId error, userId:{}", userId);
            return;
        }
        //检查下是否是内服玩家，限制购买了
        if(InnerUserMgr.isInnerBlack(userId)){
            resultObj = getResultObj(GameErrorCode.E_RECHARGE_ACCOUNT_EXCEPTION, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge limit, userId:{}", userId);
            return;
        }
        ret = GameWebServiceInvoke.queryRechargeSwitchOpen(userId);
        if (ret != 0) {
            resultObj = getResultObj(ret, language);
            sendMessage(response, resultObj.toJSONString());
            return;
        }
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if(null == mallInfo){
            resultObj = getResultObj(GameErrorCode.E_MALL_NO_EXIST, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge fail, mallInfo no find, mallId:{}", mallId);
            return;
        }
        if(ePreChargeType.normalBuy.getValue() != type && ePreChargeType.activityBuy.getValue() != type){
            resultObj = getResultObj(GameErrorCode.E_PRE_CHARGE_TYPE_ERROR, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge fail, preChargeType error, type:{}", type);
            return;
        }
        if(ePreChargeType.activityBuy.getValue() == type){
            try {
                activityId = paramObj.getIntValue("activityId");
                conditionId = paramObj.getIntValue("conditionId");
            } catch (Exception e) {
                resultObj = getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language);
                sendMessage(response, resultObj.toJSONString());
                logger.error("PreCharge json格式出错！ json 字符串param为{}", param, e);
                return;
            }
        }
        String queryResult = GameWebServiceInvoke.queryMallCanBuy(activityId, mallId, userId, couponItemId);
        if(StringUtils.isNullOrEmpty(queryResult)){
            queryResult = "";
        }
        JSONObject queryResultObj = JSON.parseObject(queryResult);
        ret = queryResultObj.getIntValue("ret");
        int couponGoodsId = queryResultObj.getIntValue("couponGoodsId");
        if(0 != ret){
            resultObj = getResultObj(ret, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("PreCharge fail, ret:{}", ret);
            return;
        }

        String orderNo = OrderHelper.generateOrderNum();
        int vipExp = (int) MallRechargeConfigMgr.getParamValue(mallInfo);
//        int vipExp = Integer.parseInt(mallInfo.getParam());
        String mallName = MallMgr.getMallName(mallInfo, language);
        long returnIngots = MallRechargeConfigMgr.getReturnIngots(mallInfo);
        long price = MallRechargeConfigMgr.getPrice(mallInfo);
        RechargeOrder rechargeOrder = initRechargeOrder(orderNo, userId, price, mallId, type, activityId, conditionId,
                returnIngots, vipExp, mallInfo.getShopType(), mallName, mallInfo.getMallMarkId(), couponItemId, couponGoodsId);
        if (!RechargeBussiness.addRechargeOrder(rechargeOrder)) {
            resultObj = getResultObj(GameErrorCode.E_PRE_CHARGE_SAVE_ORDER_ERROR, language);
            sendMessage(response, resultObj.toJSONString());
            logger.error("preCharge save db fail. playerId:{}, orderNo:{}, mallId:{}", userId, orderNo, mallId);
            return;
        }
        resultObj = getResultObj(0, language);
        resultObj.put("orderNum", orderNo);
        GameWebServiceInvoke.logPreRecharge(userId, orderNo, mallId);
        logger.info("preCharge success. playerId:{}, orderNo:{}, mallId:{}", userId, orderNo, mallId);
        sendMessage(response, resultObj.toString());
    }

    private RechargeOrder initRechargeOrder(String orderNo, long userId, long totalFee, int mallId, int preChargeType, int activityId, int conditionId,
            long returnIngots, int addVipExp, int shopType, String mallName, int mallMarkId, long couponItemId, int couponGoodsId) {
        RechargeOrder order = new RechargeOrder();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setAmount(totalFee);
        order.setOrderStatus(eOrderStatus.PreOrder);
        order.setMallId(mallId);
        order.setPreChargeType(preChargeType);
        order.setActivityId(activityId);
        order.setConditionId(conditionId);
        order.setReturnIngots(returnIngots);
        order.setAddVipExp(addVipExp);
        order.setShopType(shopType);
        order.setMallName(mallName);
        order.setMallMarkId(mallMarkId == 0 ? mallId : mallMarkId);
        order.setCouponItemId(couponItemId);
        order.setCouponGoodsId(couponGoodsId);
        return order;
    }
}
